<template>
  <view class="container">
    <view class="status-bar">
      <view class="status-title" v-if="status == 5">
        <u-icon size="22" name="close" class="icon"></u-icon>
        订单已取消
        <view class="status-description"> 订单因长时间未付款，交易已经取消 </view>
      </view>
      <view class="status-title" v-else>
        <u-icon size="60" name="coupon" class="icon"></u-icon>
        <span v-if="status == 1">待到店使用</span>
        <span v-else>待付款，还剩 <u-count-down :time="time" format="mm:ss" class="count-down"
            @finish="handleFinish" /></span>
      </view>
    </view>
    <view class="order-details" v-if="status == 1">
      <view class="details-text"> 请尽快核销您的订单 </view>
    </view>
    <view class="order-info-container">
      <view class="activity-name">
        {{ formData.activeName }}
      </view>
      <view class="order-info">
        <image :src="getImg + formData.icon" class="activity-icon" />
        <view class="info-text">
          <p class="ellipsis">{{ formData.ticketName }}</p>
          <p style="font-size: 12px; margin-top: 5px">{{ formData.merName }}</p>
          <view class="info-row">
            <view class="info-left">
              数量<span class="number">X{{ formData.totalNum }}</span>
            </view>
            <view class="info-right" @click="getDetail">
              实付<span class="price">￥{{ formData.payPrice }}</span>
              <u-icon name="arrow-right" />
            </view>
          </view>
        </view>
      </view>
      <view v-if="status == 1">
        <view
          style="display: flex; align-items: center; justify-content: center; margin-top: 100rpx; margin-bottom: 50rpx">
          <tki-qrcode ref="qrcode" :cid="cid" :val="qrValue" size="300" :unit="unit" background="#fff"
            :foreground="foreground" :pdground="pdground" :icon="icon" :iconSize="iconsize" :onval="onval"
            :loadMake="loadMake" :usingComponents="usingComponents" :showLoading="showLoading"
            :loadingText="loadingText" @result="qrR" />
          <!-- <button @click="_generateQrCode">生成二维码</button> -->
        </view>
        <u-divider />
        <view class="voucher-code-section">
          <view class="voucher-count">
            待使用券码<span class="voucher-number">{{ formData.recordList ? formData.recordList.length : 0 }}</span>张
          </view>
          <view> <button class="refund-button" plain type="default" @click="onRefund">申请退款</button></view>
        </view>
        <u-divider />
        <view class="voucher-list">
          <view class="voucher-item" v-for="(item, index) of formData.recordList" :key="index">
            <view class="voucher-code">
              · {{ item.ticketCode }}
              <span class="copy-button" @click="onCopy(item.ticketCode)">复制</span>
            </view>
          </view>
        </view>
      </view>
    </view>
    <orderAddress :formData="formData" />
    <orderInfo :isPayTime="status == 1" :formData="formData" />
    <view v-if="status == 0" class="payment-section">
      <!-- <payment ref="payment" @onChange="onChange" /> -->
    </view>
    <view v-if="status == 0" class="action-buttons">
      <!-- <u-button class="submit-button" round type="default" :loading="cancelLoading" @click="onCancel">取消订单</u-button> -->
      <u-button class="submit-button" round type="primary" :loading="loading" @click="onSubmit">￥{{ formData.payPrice }}
        继续支付</u-button>
    </view>
    <priceDetail ref="priceDetail" :orderId="orderId" />
  </view>
</template>

<script>
import TkiQrcode from "../../../components/tki-qrcode/tki-qrcode.vue";
import orderInfo from "../../../pages_sh/orderCode/components/order_info.vue";
import { IMG_URL } from "../../../config/index.js";
import priceDetail from "../../../pages_sh/orderCode/components/price_detail.vue";
import orderAddress from "./order_address.vue";
import { toBeUsedOrPay, orderCancel, orderList } from "../../../utils/api/local";
import getOrderPay from "../../../utils/api/getOrderPay.js";
export default {
  mixins: [getOrderPay],

  components: {
    priceDetail,
    orderInfo,
    orderAddress,
    TkiQrcode,
    // payment,
  },
  data() {
    return {
      cid: "tki-qrcode-canvas",
      qrValue: "",
      unit: "upx",
      foreground: "#000000",
      pdground: "#000000",
      icon: "",
      iconsize: 40,
      onval: false,
      loadMake: true,
      usingComponents: true,
      showLoading: true,
      loadingText: "二维码生成中",
      getImg: IMG_URL,
      time: 1800000,
      status: 1,
      orderId: "",
      id: "",
      formData: {
        recordList: [],
      },
      cancelLoading: false,
      fileList: [],
      orderType: "pay_ls",
      jishi: null,
    };
  },
  onLoad(option) {
    this.orderId = option.orderId;
    this.id = option.id;
    this.status = option.status;
    this.toBeUsedOrPay();
  },
  mounted() {
    if (this.status == 1) {
      this.jishi = setInterval(() => {
        this.fetchOrderList();
      }, 2000);
    }
  },
  /* 离开界面也要清除定时器 */
  onUnload() {
    this.cleartime();
  },
  onShow() {
    this.toBeUsedOrPay();
  },
  methods: {
    /* 清楚计时器 */
    cleartime() {
      clearInterval(this.jishi);
    },
    /* 每两秒执行一次判断状态是否为1.不为1就核销成功 */
    fetchOrderList() {
      toBeUsedOrPay({
        orderId: this.orderId,
      }).then((res) => {
        if (res.data.storeOrder.status != 1) {
          uni.showToast({
            title: "订单核销成功",
            icon: "none",
          });
          this.cleartime();
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages_h5/myCenter/components/local_life_order",
              success: function (e) {
                var page = getCurrentPages()[0]; //相当于被跳转页面的选择器
                if (page == undefined || page == null) {
                  //判断页面是否存在
                  return;
                } else {
                  page.$vm.getData();
                }
              },
            });
          }, 1500);
        }
      });
    },

    // 定义一个方法来调用子组件的 _makeCode 方法
    _generateQrCode() {
      this.$refs.qrcode._makeCode();
    },
    // 处理二维码生成结果的方法
    qrR(result) {
      console.log("二维码生成结果:", result);
    },
    getcode() {
      this.$refs.qrcode._saveCode();
    },
    onChange(type) {
      console.log(1);
      this.orderType = type;
    },
    handleFinish() {
      this.status = 5;
    },
    toBeUsedOrPay() {
      toBeUsedOrPay({
        orderId: this.orderId,
      }).then((res) => {
        this.formData = res.data.storeOrder || {};
        this.formData.activeName = res.data.ebMerActivity.name;
        this.formData.ticketName = res.data.ebMerActivityTicket.name;
        this.formData.merName = res.data.ebMer.merName;
        this.formData.recordList = res.data.ebMerActivityTicketRecordList || [];
        this.formData.businessTime = res.data.ebMer.businessTime;
        this.formData.merAddress = res.data.ebMer.merAddress;
        this.formData.merAvatar = res.data.ebMerActivityTicket.merAvatar;
        this.formData.orderId = this.orderId;
        this.formData.icon = res.data.ebMerActivity.icon;
        this.formData.merPhone = res.data.ebMer.merPhone;
        this.id = res.data.storeOrder.id;
        if (res.data.ebMerActivityTicketRecordList && res.data.ebMerActivityTicketRecordList.length) {
          this.formData.endTime = res.data.ebMerActivityTicketRecordList[0].endTime;
        }
        let date = new Date();
        let milliseconds = date.getTime();
        let createDate = new Date(this.formData.createTime || 0);
        let createTime = createDate.getTime() || 0;
        this.time = 1800000 - (milliseconds - createTime);
        /** 生成二维码券码 */
        if (this.status == 1) {
          if (this.formData.recordList && this.formData.recordList.length) {
            let code = this.formData.recordList[0].ticketCode;
            this.qrValue = `https://www.wantongkonggu.cn/apph7/pages_sh/orderCode/redempt?ticketCode=${code}`;
            this._generateQrCode();
          }
          this.fetchOrderList();
        }
      });
    },
    onCopy(text) {
      uni.setClipboardData({
        data: text,
        success: () => {
          uni.showToast({
            title: "复制成功",
            icon: "success",
          });
        },
      });
    },
    getDetail() {
      console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
      this.$refs.priceDetail.handleOpen();
    },
    onRefund() {
      uni.navigateTo({
        url: "/pages_h5/local_life/components/refund?status=6&orderId=" + this.orderId + "&id=" + this.id,
      });
    },
    onCancel() {
      uni.showModal({
        title: "取消订单",
        content: "此操作将会取消此订单，请确定是否执行此操作？",
        success: (modelRes) => {
          if (modelRes.confirm) {
            this.cancelLoading = true;
            orderCancel({
              id: this.id,
              orderId: this.orderId,
            })
              .then((res) => {
                this.cancelLoading = false;
                uni.showToast({
                  title: "取消成功",
                })
                uni.navigateBack({
                  delta: 1,
                });
              })
              .catch(() => {
                uni.showToast({
                  title: "出错了，请稍后再试",
                })
                this.cancelLoading = false;
              });
          }
        },
      });
    },
    onSubmit() {
      if (this.orderType === "pay_yue" && Number(this.userInfo.nowMoney || 0) < Number(this.formData.payPrice || 0)) {
        uni.showToast({
          title: "所需金额大于账号余额，请先充值",
        })
        return false;
      }
      this.loading = true;
      this.getOrderPay({
        id: this.id,
        orderNo: this.orderId,
        tab: 3,
        goPagesSuccess: 1,
        goPagesFail: 0,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  height: 100vh;
  position: relative;
  padding: 20rpx;
}

.status-bar {
  display: flex;
  align-items: center;
}

.status-title {
  display: flex;
  font-weight: 600;
  font-size: 22px;
}

.icon {
  margin-right: 10rpx;
}

.status-description {
  font-size: 16px;
  margin-top: 10rpx;
  font-weight: 400;
}

.order-details {
  font-size: 16px;
  margin-top: 10rpx;
}

.order-info-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.activity-name {
  font-size: 16px;
}

.order-info {
  display: flex;
  margin-top: 20rpx;
}

.activity-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  float: left;
}

.info-text {
  margin-left: 20rpx;
  color: #666666;
  width: calc(100% - 150rpx);
}

.ellipsis {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
}

.info-left {
  font-size: 14px;
  line-height: 56rpx;
}

.number {
  margin-left: 20rpx;
}

.info-right {
  display: flex;
  align-items: center;
}

.price {
  color: #ff9500;
  font-weight: 600;
  margin-right: 10rpx;
}

.voucher-code-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
}

.voucher-count {
  line-height: 56rpx;
}

.voucher-number {
  margin-left: 10rpx;
  margin-right: 10rpx;
  color: #ff9500;
}

.refund-button {
  border-radius: 20px;
  font-size: 14px;
}

.voucher-list {
  margin-top: 20rpx;
}

.voucher-item {
  display: flex;
  margin-bottom: 20rpx;
}

.voucher-code {
  font-weight: 600;
  font-size: 16px;
  float: left;
}

.copy-button {
  background-color: #ebedf0;
  color: #666666;
  font-size: 12px;
  margin-left: 20rpx;
  padding: 5rpx 10rpx;
  border-radius: 8rpx;
}

.payment-section {
  margin-top: 20rpx;
}

.action-buttons {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 20rpx 0;
}

.cancel-button {
  width: 240rpx;
  border-radius: 100rpx;
  font-weight: 400;
}

.submit-button {
  width: calc(100% - 310rpx);
  border-radius: 100rpx;
  margin-left: 20rpx;
  font-weight: 400;
}

.count-down {
  color: #ff9500;
  display: inline-block;
  font-size: 44rpx;
}
</style>
